#! /usr/bin/env python
# -*- coding: utf-8 -*-

from django.shortcuts import render, HttpResponse, redirect
from web.form.account import RegisterModelForm, SmsForm, LoginSmsForm, LoginForm
from django.http import JsonResponse
from web import models
import uuid, datetime
import logging
logger = logging.getLogger('log')

"""
用户账户相关功能： 注册、短信、登录、注销等
"""


def register(request):
    """ 注册 """
    # return render(request, "register.html")
    if request.method == "GET":
        form = RegisterModelForm()
        return render(request, "register.html", {"form": form})

    if request.method == "POST":
        form = RegisterModelForm(data=request.POST)
        # print(form)
        if form.is_valid():
            # 密码在form中加密
            instance = form.save()
            # 获取价格策略
            price_policy = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
            # 创建交易记录
            models.Transaction.objects.create(
                status=2,
                order=str(uuid.uuid4()),
                user=instance,
                price_policy=price_policy,
                count=0,
                price=0,
                start_datetime=datetime.datetime.now()

            )
            logger.info(f"[register] username: {request.POST.get('username')}")
            return JsonResponse({'status': True, 'data': '/login/'})
        return JsonResponse({'status': False, 'err': form.errors})


def send_sms(request):
    """ 发送验证码 """

    form = SmsForm(request, data=request.POST)
    # 校验手机号不能为空、格式是否正确
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'err': form.errors})


def login(request):
    if request.method == "GET":
        form = LoginForm(request)
        return render(request, 'login.html', {"form": form})
    if request.method == "POST":
        form = LoginForm(request, data=request.POST)
        if form.is_valid():
            # username 为手机号或邮箱
            username = form.cleaned_data["username"]
            pwd = form.cleaned_data["pwd"]
            # user_obj = models.UserInfo.objects.filter(username=username, pwd=pwd).first()
            # 手机号==username && pwd == pwd or 邮箱==username && pwd==pwd
            from django.db.models import Q
            user_obj = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username))\
                .filter(pwd=pwd).first()

            if not user_obj:
                # 用户名密码错误
                form.add_error("username", "用户名或密码错误")
            else:
                # 登录成功
                request.session['user_id'] = user_obj.id
                request.session.set_expiry(60*60*24*14)
                return redirect('index')
        return render(request, 'login.html', {'form': form})


def login_sms(request):
    """短信登录"""
    if request.method == "GET":
        form = LoginSmsForm()
        return render(request, 'login_sms.html', {'form': form})

    if request.method == "POST":
        form = LoginSmsForm(data=request.POST)
        if form.is_valid():
            # 登录成功
            logger.info(f"[login] username: {request.POST.get('mobile_phone')}")
            user_obj = form.cleaned_data['mobile_phone']
            # print(user_obj.mobile_phone, user_obj.email, user_obj.pwd, user_obj.username)
            request.session['user_id'] = user_obj.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return JsonResponse({'status': True, 'data': '/index/'})
        return JsonResponse({'status': False, 'err': form.errors})


def logout(request):
    request.session.flush()
    return redirect('index')


def image_code(request):
    from utils.image_code import check_code
    from io import BytesIO
    img_obj, code = check_code()
    request.session["img_code"] = code
    # 验证码超时， 主动修改过期时间60s
    request.session.set_expiry(60)
    stream = BytesIO()
    img_obj.save(stream, 'png')

    return HttpResponse(stream.getvalue())


